package com.guigusuqi.commonutils.utils;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

public class FileUtils {
    /**
     * 预览pdf文件工具类
     * @param response
     * @param fileName
     */
    public static void showPdf(HttpServletResponse response, String fileName) throws IOException {
        if(fileName.endsWith("pdf") || fileName.endsWith("PDF")){
            response.setContentType("application/pdf");
        }else if(fileName.endsWith("xls")){
            response.setContentType("application/x-xls");
        }else if(fileName.endsWith("docx")){
            response.setContentType("application/msword");
        }else if(fileName.endsWith("png")){
            response.setContentType("application/x-png");
        }else if(fileName.endsWith("jpg")){
            response.setContentType("application/x-jpg");
        }else if(fileName.endsWith("doc")){
            response.setContentType("application/msword");
        }

//        response.setContentType("image/png");
        FileInputStream in = new FileInputStream(new File(fileName));
        OutputStream out = response.getOutputStream();
        byte[] b = new byte[1024];
        while ((in.read(b))!=-1) {
            out.write(b);
        }
        out.flush();
        in.close();
        out.close();
    }

}
